package com.gpframework.aspectj;

import com.gpframework.common.constant.BrandConstants;
import com.gpframework.common.core.domain.entity.SysRole;
import com.gpframework.common.utils.StringUtils;
import com.gpframework.module.common.domain.CommonWxUser;
import com.gpframework.module.common.service.ICommonWxUserService;
import com.gpframework.module.service.TokenService;
import com.gpframework.module.system.mapper.SysRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import java.util.List;

/**
 * 用于绑定@CurrentMember的方法参数解析器
 */
@Slf4j
@Service
public class CurrentMemberMethodArgumentResolver implements HandlerMethodArgumentResolver {
    @Autowired
    private TokenService tokenService;
    @Autowired
    private ICommonWxUserService iCommonWxUserService;
    @Autowired
    private SysRoleMapper sysRoleMapper;

    @Override
    public boolean supportsParameter(MethodParameter parameter) {
        if (parameter.getParameterType().isAssignableFrom(CommonWxUser.class)
                && parameter.hasParameterAnnotation(CurrentMember.class)) {
            return true;
        }
        return false;
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer, NativeWebRequest webRequest, WebDataBinderFactory binderFactory) {
        CurrentMember currentUserAnnotation = parameter.getParameterAnnotation(CurrentMember.class);
        String token = webRequest.getHeader("Authorization");
        if (token == null) {
            log.info("从请求参数获取accessToken");
            token = webRequest.getParameter("accessToken");
        }
        if (StringUtils.isBlank(token)) {
            return null;
        }
        CommonWxUser wxUser = this.iCommonWxUserService.getById(tokenService.getMemberId(token));
        //获取用户角色
        List<SysRole> userRoleList = sysRoleMapper.getUserRoleList(wxUser.getBrandUserId());
        //所有数据权限
        String dataScope = BrandConstants.DATA_SCOPE_THIS;
        for (SysRole sysRole : userRoleList) {
            if (BrandConstants.DATA_SCOPE_ALL.equals(sysRole.getDataScope())) {
                dataScope = BrandConstants.DATA_SCOPE_ALL;
            }
        }
        wxUser.setRemarks(dataScope);
        return wxUser;
    }
}
